//
//  JXScrollBar.m
//  页面切换
//
//  Created by 尹桥印 on 14/12/19.
//  Copyright (c) 2014年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXScrollBar.h"
#import "JXPoint.h"
#import "UIView+Extension.h"

#define JXLableHeight 2
#define JXTitleFontSize 16
#define JXMargin 15

#define JXLabelWidth 30

//按钮选中的颜色
#define JXBtnSelectColor [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0]
//按钮默认的颜色
#define JXBtnNormalColor [UIColor colorWithRed:150/255.0 green:150/255.0 blue:150/255.0 alpha:1.0]
//小滑块的颜色
#define JXLabelColor [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0]

@interface JXScrollBar()

/**装button的scroll*/
@property(nonatomic,weak) UIScrollView *scrollView;
/**滑块条的lable*/
@property(nonatomic,weak) UILabel *label;
/**装有各个点的array*/
@property(nonatomic,strong) NSMutableArray *pointArray;

/**装有顶部button的array*/
@property(nonatomic,strong) NSMutableArray *buttonArray;

/**当前选中的index */
@property(nonatomic,assign) int currentSelect;

@end
@implementation JXScrollBar


-(instancetype)initWithTitleArray:(NSArray *)titleArray frame:(CGRect)frame type:(JXScrollBarSplitType)type{
    
    JXScrollBar *bar = [self initWithFrame:frame type:type];
    [bar setTitleArray:titleArray];
    return bar;
}

-(instancetype)initWithFrame:(CGRect)frame type:(JXScrollBarSplitType)type{
    self = [super init];
    if(self!=nil){
        self.frame = frame;
        _type = type;
        //先添加scrollView
        UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        
        [self addSubview:scrollView];
        _scrollView = scrollView;
        
        _pointArray = [NSMutableArray array];
        _buttonArray = [NSMutableArray array];
        
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        
        //添加label
        UILabel *label = [[UILabel alloc]init];
        _label = label;
        _label.backgroundColor = [UIColor whiteColor];
        [_scrollView addSubview:label];
    }
    return self;
    
}

-(instancetype)initWithTitleArray:(NSArray *)titleArray frame:(CGRect)frame{
    return [self initWithTitleArray:titleArray frame:frame type:JXScrollBarSplitTypeDefault];
}

-(void)setTitleArray:(NSArray *)titleArray{
    [_pointArray removeAllObjects];
    [_buttonArray makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_buttonArray removeAllObjects];
    for (int i=0; i<titleArray.count; i++) {
        NSString *str = titleArray[i];
        UIButton *button = [[UIButton alloc]init];
        [button.titleLabel setFont:[UIFont systemFontOfSize:JXTitleFontSize]];
        [button setTitleColor:JXBtnSelectColor forState:UIControlStateSelected];
        [button setTitleColor:JXBtnNormalColor forState:UIControlStateNormal];
        [button setTitle: str forState: UIControlStateNormal];
        [button setTag:i];
        [button addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        
        CGSize size = [str sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:JXTitleFontSize],NSFontAttributeName, nil]];
        int width = size.width;
        int x = 0;
        if([_pointArray lastObject]){
            JXPoint *p = [_pointArray lastObject];
            x = p.x+p.width;
        }
        
        if(i==_currentSelect){
            button.selected = YES;
        }
        JXPoint *point = nil;
        
        if(_type==JXScrollBarSplitTypeDefault){
            point = [JXPoint initWithContentWidth:width width:width+JXMargin*2 x:x];
            button.frame = CGRectMake(x, 0, width+JXMargin*2, self.frame.size.height-JXLableHeight);
        }else{
            //平均
            int tempWidth = self.width/titleArray.count;
            point = [JXPoint initWithContentWidth:width width:tempWidth x:x];
            button.frame = CGRectMake(x, 0, tempWidth, self.frame.size.height-JXLableHeight);
        }
        
        [_pointArray addObject:point];
        [_buttonArray addObject:button];
        [_scrollView addSubview:button];
        
    }
    
    int x = 0;
    if([_pointArray lastObject]){
        JXPoint *p = [_pointArray lastObject];
        x = p.x+p.width;
    }
    //如果不是放在顶部里面，需要打开这句代码
    //        _scrollView.contentInset =UIEdgeInsetsMake(-64,0, 0, 0);
    _scrollView.contentSize = CGSizeMake(x, 30);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if(!_pointArray.count)return;
    
    int pageNum = (scrollView.contentOffset.x+self.frame.size.width*0.5)/self.frame.size.width;
    [self selectButton:pageNum];
    
    
    //在这个地方动态计算出uilabel的x,y,weight;
    
    double f = scrollView.contentOffset.x/scrollView.frame.size.width;
    if (f<0) {
        f = 0;
    }else if (f>_pointArray.count-1){
        f = _pointArray.count-1;
    }
    
    int currentPage = (int)f;
    
    double offset = f-currentPage;
    // 1.先计算出宽度，如果当前是第0个页面，那个width的宽度为第0个标签的长度
    JXPoint *currentP = _pointArray[currentPage];
    JXPoint *nextP = nil;
    if(currentPage+1>=_pointArray.count){
        nextP =_pointArray[currentPage];
    }else{
        nextP = _pointArray[currentPage+1];
    }
    
    double width = 0;
    double x = 0;
    if(_type==JXScrollBarSplitTypeDefault){
        //宽度与当前标签宽度加上当前标签与下一个标签增量比乘以(当前标签与下一个标签内容的差)
        width = currentP.contentWidth+offset*(nextP.contentWidth-currentP.contentWidth);
        //计算中点
        x = (currentP.x+currentP.width/2)+((nextP.x+nextP.width/2)-(currentP.x+currentP.width/2))*offset-width/2;
    }else{
        width = currentP.width;
        x = f*scrollView.width/_pointArray.count;
    }
    double y = self.height-JXLableHeight-10;
    
    _label.frame = CGRectMake(x, y, width, JXLableHeight);
    
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //当前页数
    int pageNum = (scrollView.contentOffset.x+self.frame.size.width*0.5)/self.frame.size.width;
    
    [self autoScrollToCenter:pageNum];
}

//将当前选中标签滚动到指定位置
-(void)autoScrollToCenter:(int)pageNum{
    
    [self selectButton:pageNum];
    
    JXPoint *currentP = _pointArray[pageNum];
    //当前页数对应标签的中心点在scrollView的位置
    double pointCenterX = currentP.x+currentP.width*0.5;
    
    //整个view宽度的一半
    double viewWidth2 = self.width/2;
    
    CGFloat duration = 0.25;
    double offset = 0;
    
    //如果该button的中间位置大于view的中间位置
    if(pointCenterX>viewWidth2){
        offset = pointCenterX-viewWidth2;
        if(_scrollView.contentSize.width<=self.width){
            offset = 0;
        }else{
            //如果当前偏移量加上整个view的一半再加上当前标签宽度的一半大于或者等于整个scrollView的内容宽度
            //就是滑动到最后一页或几页了
            if((pointCenterX+viewWidth2)>=_scrollView.contentSize.width){
                offset = _scrollView.contentSize.width-self.width;
            }
        }
    }
    [UIView animateWithDuration:duration animations:^{
        [_scrollView setContentOffset:CGPointMake(offset, 0)];
    }];
}

-(void)selectButton:(int)pageNum{
    //当前页数
    
    if(pageNum!=_currentSelect){
        if(pageNum>=_buttonArray.count)return;
        UIButton *newBtn = _buttonArray[pageNum];
        newBtn.selected = YES;
        
        UIButton *oldBtn = _buttonArray[_currentSelect];
        oldBtn.selected = NO;
        
        _currentSelect = pageNum;
    }
}

-(void)titleClick:(UIButton *)button{
    int selectPage = (int)button.tag;
    if(_currentSelect==selectPage)return;
    if ([self.delegate respondsToSelector:@selector(titleClicked:index:)]) {
        [self.delegate titleClicked:self index:selectPage];
    }
}

@end
